package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.domain.vo.SysDept_mini;
import com.ruoyi.system.mapper.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.service.ISysDeptService;

import javax.annotation.Resource;

/**
 * 部门管理 服务实现
 *
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
    @Resource
    private SysDeptMapper deptMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysUserRoleMapper userRoleMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private DoseMapper doseMapper;
    @Resource
    private DoseDetailMapper doseDetailMapper;
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private MenuDetailMapper menuDetailMapper;
    @Resource
    private MealMapper mealMapper;
    @Resource
    private MealDetailMapper mealDetailMapper;
    @Resource
    private CateMapper cateMapper;
    @Resource
    private TypeMapper typeMapper;
    @Resource
    private SpecMapper specMapper;
    @Resource
    private BrandMapper brandMapper;
    @Resource
    private RedisCache redisCache;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept) {
        List<SysDept> sysDeptS = deptMapper.selectDeptList(dept);
        Map<Long, Cate> cateMap = cateMapper.selectCateList(new Cate()).stream().collect(Collectors.toMap(Cate::getId, t -> t));
        for (SysDept sysDept : sysDeptS) {
            if (sysDept.getType() != null) {
                if (sysDept.getType() == 0) {
                    StringBuilder cateStr = new StringBuilder();
                    for (String cateId : sysDept.getCate().split(",")) {
                        if (cateMap.containsKey(Long.valueOf(cateId))) {
                            cateStr.append(cateMap.get(Long.valueOf(cateId)).getName()).append(",");
                        }
                    }
                    if (cateStr.length() > 0) {
                        sysDept.setCateStr(cateStr.substring(0, cateStr.lastIndexOf(",")));
                    }
                }
            }
        }

        return sysDeptS;
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept_mini> selectDeptList_mini(SysDept dept) {
        List<SysDept_mini> resList = new ArrayList<>(10);
        List<SysDept> sysDeptS = deptMapper.selectDeptList(dept);
        for (SysDept sysDept : sysDeptS) {
            resList.add(new SysDept_mini(sysDept.getDeptId(), sysDept.getDeptName()));
        }

        return resList;
    }

    @Override
    public List<SysDept> selectDeptList_anonymous(SysDept dept) {
        List<SysDept> sysDeptS = deptMapper.selectDeptList(dept);

        //获取redis中在线人员列表
        Map<Long, List<Long>> userMap = new HashMap<>();
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");

        for (String key : keys) {
            LoginUser user = redisCache.getCacheObject(key);
            List<Long> longs;
            if (userMap.containsKey(user.getDeptId())) {
                longs = userMap.get(user.getDeptId());
            } else {
                longs = new ArrayList<>();
            }
            longs.add(user.getUserId());
            userMap.put(user.getDeptId(), longs);
        }

        for (SysDept sysDept : sysDeptS) {

            if (userMap.containsKey(sysDept.getDeptId())) {
                sysDept.setOnlineFlag(0);
            } else {
                sysDept.setOnlineFlag(1);
            }

        }

        return sysDeptS;
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept) {
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && StringUtils.isNotNull(deptId)) {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insertDept(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept) {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        return deptMapper.deleteDeptById(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }


    /**
     * 格式化公司数据,从原库的company表，导入到sys_dept表中
     */
    @Override
    public void formatCompanyData() {
        List<Company> companyList = deptMapper.selectCompanyList();
        List<SysDept> sysDeptList = new ArrayList<>(10);
        companyList.forEach(item -> {
            SysDept sysDept = new SysDept();
            sysDept.setDeptId(Long.valueOf(String.valueOf(item.getId())));
            sysDept.setParentId(1000002L);
            sysDept.setAncestors("0,1000001,1000002");
            sysDept.setDeptName(item.getCompany_name());
            sysDept.setOrderNum(1);
            sysDept.setLeader(item.getName());
            sysDept.setPhone(item.getPhone());
            sysDept.setEmail(item.getEmail());
            sysDept.setStatus("0");
            sysDept.setCreateBy("admin");
            sysDept.setCreateTime(new Date(item.getCreate_time()));
            sysDept.setLicense(item.getLicense());
            sysDept.setCode(item.getCode());
            sysDept.setFood(item.getFood());
            sysDept.setIdCardTop(item.getId_card_top());
            sysDept.setIdCardBack(item.getId_card_back());
            sysDept.setFoodInspector(item.getFood_inspector());
            sysDept.setHealth(item.getHealth());
            sysDept.setPerformance(item.getPerformance());
            sysDept.setCate(item.getCate());
            sysDept.setNature(item.getNature());
            sysDept.setAptitude(item.getAptitude());
            sysDept.setAddress(item.getAddress());
            sysDept.setArea(item.getArea());
            sysDept.setEquity(item.getEquity());
            sysDept.setEquityCert(item.getEquity_cert());
            sysDept.setIso9001(item.getIso9001());
            sysDept.setIso14001(item.getIso14001());
            sysDept.setHaccp(item.getHaccp());
            sysDept.setCnas(item.getCnas());
            sysDept.setCar(item.getCar());
            sysDept.setCarNum1(item.getCar_num1());
            sysDept.setCarNum2(item.getCar_num2());
            sysDept.setIsCar(item.getIs_car());
            sysDept.setFoodInsurance(item.getFood_insurance());
            sysDept.setSumInsured(item.getSum_insured());
            sysDept.setSocialSecurity(item.getSocial_security());
            sysDept.setOther(item.getOther());
            sysDept.setNotOpen(item.getNot_open());
            sysDept.setLianOpen(item.getLian_open());
            sysDept.setOpen(item.getOpen());
            sysDept.setType(0);
            if (item.getStatus().equals(0)) {
                sysDept.setStatus("1");
            } else {
                sysDept.setStatus("0");
            }
            if (item.getDelete_time() != null && item.getDelete_time() != 0) {
                sysDept.setDelFlag("1");
            } else {
                sysDept.setDelFlag("0");
            }
            sysDeptList.add(sysDept);
        });
        sysDeptList.forEach(item -> {
            deptMapper.insertDept(item);
        });
    }

    /**
     * 格式化公司用户数据，从原库的admin_user中，导入到sys_user中
     */
    @Override
    public void formatAdminUserData() {
        List<User> userList = deptMapper.selectUserList();
        List<SysUser> sysUserList = new ArrayList<>(10);
        userList.forEach(item -> {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(Long.valueOf(item.getId()));
            sysUser.setDeptId(Long.valueOf(item.getCompany_id()));
            sysUser.setUserName(item.getUsername());
            sysUser.setNickName(item.getNickname());
            sysUser.setPhonenumber(item.getMobile());
            sysUser.setAvatar(item.getAvatar());
            sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            if (item.getStatus().equals(0)) {
                sysUser.setStatus("1");
            } else {
                sysUser.setStatus("0");
            }
            if (item.getDelete_time() != null && item.getDelete_time() != 0) {
                sysUser.setDelFlag("1");
            } else {
                sysUser.setDelFlag("0");
            }
            sysUser.setCreateBy("admin");
            sysUser.setCreateTime(new Date(item.getCreate_time()));
            sysUser.setLevelId(Long.valueOf(item.getUser_level_id()));
            sysUser.setType(1);
            sysUserList.add(sysUser);
        });

        sysUserList.forEach(item -> {
            sysUserMapper.insertUser(item);
            insertUserRole(item.getUserId(), new Long[]{108L});
        });
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 格式化学校数据，从原库的school中，导入到sys_user中
     */
    @Override
    public void formatSchoolData() {
        List<School> schools = deptMapper.selectSchoolList();
        List<SysDept> sysDeptList = new ArrayList<>(10);
        List<SysUser> sysUserList = new ArrayList<>(10);

        Map<String, List<School>> collect = schools.stream().collect(Collectors.groupingBy(School::getName));

        schools.forEach(item -> {
            SysDept sysDept = new SysDept();
            sysDept.setParentId(1000003L);
            sysDept.setAncestors("0,1000001,1000003");
            sysDept.setDeptName(item.getName());
            sysDept.setOrderNum(1);
            if (item.getStatus().equals(0)) {
                sysDept.setStatus("1");
            } else {
                sysDept.setStatus("0");
            }
            if (item.getDelete_time() != null && item.getDelete_time() != 0) {
                sysDept.setDelFlag("1");
            } else {
                sysDept.setDelFlag("0");
            }
            sysDept.setCreateTime(new Date(item.getCreate_time()));
            sysDept.setType(1);
            sysDept.setLeader(item.getUsername());
            if (item.getTag() != null) {
                sysDept.setTag(item.getTag());
            }
            //老系统学校id
            sysDept.setOldId(collect.get(sysDept.getDeptName()).get(0).getId());

            sysDeptList.add(sysDept);
        });
        sysDeptList.forEach(item -> {
            deptMapper.insertDept(item);
        });
        List<SysDept> sysDeptS = deptMapper.selectDeptList(new SysDept() {{
            setType(1);
        }});
        sysDeptS.forEach(item -> {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(sysUserMapper.selectUserMaxId() + 1L);
            sysUser.setDeptId(item.getDeptId());
            sysUser.setUserName(item.getLeader());
            sysUser.setNickName(item.getDeptName());
            sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            sysUser.setStatus(item.getStatus());
            sysUser.setDelFlag(item.getDelFlag());
            sysUser.setCreateBy("admin");
            sysUser.setCreateTime(item.getCreateTime());
            sysUser.setType(2);

            sysUserMapper.insertUser(sysUser);

            insertUserRole(sysUser.getUserId(), new Long[]{100L});
        });
    }

    /**
     * 格式化报量单数据
     */
    @Override
    public void formatDoseData() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//首先定义待转换的时间格式

        List<Dose_order> doseOrders = deptMapper.selectDoseOrderList();
//        List<Dose_old> dose_olds = deptMapper.selectDoseOldList();

        for (Dose_order item : doseOrders) {
            Dose dose = new Dose();
            dose.setId(Long.valueOf(DateUtils.dateTimeNow() + RandomStringUtils.random(4, false, true)));
            dose.setCode(item.getCode());
//            dose.setSchoolId(item.getsc);
            List<SysDept> sysDeptS = deptMapper.selectDeptList(new SysDept() {{
                setOldId(item.getSchool_id());
            }});
            SysDept sysDept = sysDeptS.get(0);
            dose.setSchoolId(sysDept.getDeptId());

            Timestamp timestamp = new Timestamp(item.getCreate_time());
            dose.setCreateTime(new Date(timestamp.getTime() * 1000L));

            List<Dose_old> dose_olds = deptMapper.selectDoseOldList(item.getId());

            String week = dose_olds.get(0).getWeek();
            Calendar calendar = Calendar.getInstance();
            try {
                calendar.setTime(DateUtils.parseDate(week + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            Date weekStart = calendar.getTime();
            calendar.add(Calendar.DATE, 5);
            Date weekEnd = calendar.getTime();
            dose.setWeekStart(DateUtils.parseDateToStr("yyyy-MM-dd", weekStart));
            dose.setWeekEnd(DateUtils.parseDateToStr("yyyy-MM-dd", weekEnd));


            int i = doseMapper.insertDose(dose);


            for (Dose_old doseOld : dose_olds) {
                String detail = doseOld.getDetail();
                selectDoseVOList(detail, doseOld, sysDept, dose);
                //单品
                selectDoseVOList_detail2(doseOld.getDetail2(), doseOld, sysDept, dose);
            }


        }

    }

    public void selectDoseVOList_detail2(String detail2, Dose_old doseOld, SysDept sysDept, Dose dose) {
        JSONArray objects = JSON.parseArray(detail2);
        for (Object object : objects) {
            String jsonString = JSON.toJSONString(object);
            JSONObject jsonObject = JSON.parseObject(jsonString);

            DoseDetail doseDetail = new DoseDetail();
            doseDetail.setType(sysDept.getTag());
            doseDetail.setOrderId(dose.getId());
            doseDetail.setWeek(doseOld.getWeek());
            String[] dateStr = doseOld.getWeek().split("-");
            LocalDate localDate = LocalDate.of(Integer.parseInt(dateStr[0])
                    , Integer.parseInt(dateStr[1])
                    , Integer.parseInt(dateStr[2]));
            doseDetail.setWeekTag("周" + localDate.getDayOfWeek().getValue());
            //doseDetail.setTime(unicodeDecode(jsonObject.getString("time")));
            doseDetail.setTypeId((long) jsonObject.getIntValue("type_id"));
            doseDetail.setSpecId((long) jsonObject.getIntValue("spec_id"));
            doseDetail.setBrandId((long) jsonObject.getIntValue("brand_id"));
            doseDetail.setSchoolId(dose.getSchoolId());
            if (jsonObject.getString("num") != null && !"".equals(jsonObject.getString("num"))) {
                System.out.println(jsonObject.toJSONString());

                StringBuilder sb = new StringBuilder();


                for (char c : jsonObject.getString("num").toCharArray()) {
                    if (Character.isDigit(c)) {
                        sb.append(c);
                    }
                }

                doseDetail.setNum(new BigDecimal(sb.toString()));
            } else {
                doseDetail.setNum(BigDecimal.ZERO);
            }

            doseDetail.setCreateTime(dose.getCreateTime());

            Type type = typeMapper.selectTypeById(doseDetail.getTypeId());
            if (type != null) {
                doseDetail.setCateId(type.getCateId());
            }
            doseDetailMapper.insertDoseDetail(doseDetail);
        }
    }

    public void selectDoseVOList(String detail, Dose_old doseOld, SysDept sysDept, Dose dose) {

        List<DoseDetail> doseDetails = new ArrayList<>();
        JSONArray objects = JSON.parseArray(detail);

        //初中
        if (sysDept.getTag().equals(1)) {
            for (Object object : objects) {
                String jsonString = JSON.toJSONString(object);
                JSONObject jsonObject = JSON.parseObject(jsonString);
                JSONArray meal = jsonObject.getJSONArray("meal");
                for (Object o : meal) {
                    String jsonString1 = JSON.toJSONString(o);
                    JSONObject jsonObject1 = JSON.parseObject(jsonString1);
                    JSONArray meal1 = jsonObject1.getJSONArray("menu");
                    if (meal1 != null) {
                        for (Object o1 : meal1) {
                            String jsonString2 = JSON.toJSONString(o1);
                            JSONObject jsonObject2 = JSON.parseObject(jsonString2);

                            DoseDetail doseDetail = new DoseDetail();
                            doseDetail.setType(sysDept.getTag());
                            doseDetail.setOrderId(dose.getId());
                            doseDetail.setWeek(doseOld.getWeek());
                            String[] dateStr = doseOld.getWeek().split("-");
                            LocalDate localDate = LocalDate.of(Integer.parseInt(dateStr[0])
                                    , Integer.parseInt(dateStr[1])
                                    , Integer.parseInt(dateStr[2]));
                            doseDetail.setWeekTag("周" + localDate.getDayOfWeek().getValue());
                            doseDetail.setTime(unicodeDecode(jsonObject.getString("time")));
                            doseDetail.setMenuId((long) jsonObject1.getIntValue("menu_id"));
                            doseDetail.setTypeId((long) jsonObject2.getIntValue("type_id"));
                            doseDetail.setSpecId((long) jsonObject2.getIntValue("spec_id"));
                            doseDetail.setBrandId((long) jsonObject2.getIntValue("brand_id"));
                            doseDetail.setSchoolId(dose.getSchoolId());
                            if (jsonObject2.getString("num") != null && !"".equals(jsonObject2.getString("num"))) {
                                System.out.println(jsonObject2.toJSONString());

                                StringBuilder sb = new StringBuilder();


                                for (char c : jsonObject2.getString("num").toCharArray()) {
                                    if (Character.isDigit(c)) {
                                        sb.append(c);
                                    }
                                }

                                doseDetail.setNum(new BigDecimal(sb.toString()));
                            } else {
                                doseDetail.setNum(BigDecimal.ZERO);
                            }

                            doseDetail.setCreateTime(dose.getCreateTime());

                            Type type = typeMapper.selectTypeById(doseDetail.getTypeId());
                            if (type != null) {
                                doseDetail.setCateId(type.getCateId());
                            }

                            doseDetailMapper.insertDoseDetail(doseDetail);
                        }
                    }
                }
            }
        }
        //小学
        else if (sysDept.getTag().equals(0)) {
            for (Object object : objects) {
                String jsonString = JSON.toJSONString(object);
                JSONObject jsonObject = JSON.parseObject(jsonString);
                DoseDetail doseDetail = new DoseDetail();
                doseDetail.setType(sysDept.getTag());
                doseDetail.setOrderId(dose.getId());
                doseDetail.setWeek(doseOld.getWeek());
                String[] dateStr = doseOld.getWeek().split("-");
                LocalDate localDate = LocalDate.of(Integer.parseInt(dateStr[0])
                        , Integer.parseInt(dateStr[1])
                        , Integer.parseInt(dateStr[2]));
                doseDetail.setWeekTag("周" + localDate.getDayOfWeek().getValue());
                doseDetail.setTime(unicodeDecode(jsonObject.getString("time")));
//                doseDetail.setMenuId((long) jsonObject1.getIntValue("menu_id"));
                doseDetail.setMealId((long) jsonObject.getIntValue("meal_id"));

                List<MealDetail> mealDetails = mealDetailMapper.selectMealDetailList(new MealDetail() {{
                    setMealId(doseDetail.getMealId());
                }});
                if (!mealDetails.isEmpty()) {
                    mealDetails.forEach(item -> {
                        List<MenuDetail> menuDetails = menuDetailMapper.selectMenuDetailList(new MenuDetail() {{
                            setMenuId(item.getMenuId());
                        }});
                        for (MenuDetail menuDetail : menuDetails) {

                            Type type = typeMapper.selectTypeById(menuDetail.getTypeId());
                            if (type != null) {
                                doseDetail.setCateId(type.getCateId());
                            }

                            doseDetail.setTypeId(menuDetail.getTypeId());
                            doseDetail.setSpecId(menuDetail.getSpecId());
                            doseDetail.setBrandId(menuDetail.getBrandId());

                            doseDetail.setSchoolId(dose.getSchoolId());
                            //num是原用餐人数，要与菜谱的材料数量相乘
                            if (jsonObject.getString("num") != null && !"".equals(jsonObject.getString("num"))) {
                                doseDetail.setNum(new BigDecimal(jsonObject.getString("num")).multiply(menuDetail.getNum()));
                            } else {
                                doseDetail.setNum(BigDecimal.ZERO);
                            }
                            doseDetail.setCreateTime(dose.getCreateTime());
                            doseDetailMapper.insertDoseDetail(doseDetail);
                        }
                    });
                } else {
                    doseDetail.setSchoolId(dose.getSchoolId());
                    //num是原用餐人数，要与菜谱的材料数量相乘
                    if (jsonObject.getString("num") != null && !"".equals(jsonObject.getString("num"))) {
                        doseDetail.setNum(new BigDecimal(jsonObject.getString("num")));
                    } else {
                        doseDetail.setNum(BigDecimal.ZERO);
                    }
                    doseDetail.setCreateTime(dose.getCreateTime());
                    doseDetailMapper.insertDoseDetail(doseDetail);
                }


            }
        }


//        canteenAreaMapper.insertDoseDetail(new HashMap<String, Object>() {{
//            put("details", doseDetails);
//        }});

//        return null;
    }


    public static String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

    /**
     * 格式化菜谱表数据
     */
    @Override
    public void formatMenuData() {
        List<Menu_old> menuOlds = deptMapper.selectMenuOldList();
        for (Menu_old menuOld : menuOlds) {
            Menu menu = new Menu();
            menu.setId(Long.valueOf(menuOld.getId()));
            menu.setCate(Long.valueOf(menuOld.getCate()));
            menu.setOldId(Long.valueOf(menuOld.getOld_id()));
            menu.setTag(Long.valueOf(menuOld.getTag()));
            menu.setName(menuOld.getName());
            menu.setCreateTime(new Date(menuOld.getCreate_time() * 1000L));
            if (menuOld.getDelete_time() != 0) {
                menu.setDeleted(1);
            }
            int i = menuMapper.insertMenu(menu);
            String detail = menuOld.getDetail();
            JSONArray objects = JSON.parseArray(detail);
            objects.forEach(item -> {
                String jsonString = JSON.toJSONString(item);
                JSONObject jsonObject = JSON.parseObject(jsonString);
                MenuDetail menuDetail = new MenuDetail();
                menuDetail.setTypeId(Long.valueOf(jsonObject.getString("type_id")));
                if (jsonObject.getString("num") != null && !"".equals(jsonObject.getString("num"))) {
                    System.out.println(jsonObject.toJSONString());

                    StringBuilder sb = new StringBuilder();


                    for (char c : jsonObject.getString("num").toCharArray()) {
                        if (Character.isDigit(c)) {
                            sb.append(c);
                        }
                    }

                    menuDetail.setNum(new BigDecimal(sb.toString()));
                } else {
                    menuDetail.setNum(BigDecimal.ZERO);
                }
                menuDetail.setSpecId(Long.valueOf(jsonObject.getString("spec_id")));
                menuDetail.setBrandId(Long.valueOf(jsonObject.getString("brand_id")));
                menuDetail.setMenuId(menu.getId());
                menuDetailMapper.insertMenuDetail(menuDetail);
            });
        }
    }

    /**
     * 格式化套餐表数据
     */
    @Override
    public void formatMealData() {
        List<Meal_old> mealOlds = deptMapper.selectMealOldList();
        mealOlds.forEach(item -> {
            Meal meal = new Meal();
            meal.setId(Long.valueOf(item.getId()));
            meal.setCate(Long.valueOf(item.getCate()));
            meal.setOldId(Long.valueOf(item.getOld_id()));
            meal.setTag(Long.valueOf(item.getTag()));
            meal.setName(item.getName());
            meal.setCreateTime(new Date(item.getCreate_time() * 1000L));
            if (item.getDelete_time() != 0) {
                meal.setDeleted(1);
            }
            mealMapper.insertMeal(meal);

            String detail = item.getDetail();
            JSONArray objects = JSON.parseArray(detail);
            for (Object object : objects) {
                String jsonString = JSON.toJSONString(object);
                JSONObject jsonObject = JSON.parseObject(jsonString);
                MealDetail mealDetail = new MealDetail();
                mealDetail.setMealId(meal.getId());
                mealDetail.setMenuId((long) jsonObject.getIntValue("menu_id"));
                mealDetail.setCreateTime(meal.getCreateTime());
                mealDetailMapper.insertMealDetail(mealDetail);
            }

        });

    }

    /**
     * 格式化行业类目表数据
     */
    @Override
    public void formatCateData() {
        List<Cate_old> cateOlds = deptMapper.selectCateOldList();
        cateOlds.forEach(item -> {
            Cate cate = new Cate();
            cate.setId(Long.valueOf(item.getId()));
            cate.setName(item.getName());
            cate.setCreateTime(new Date(item.getCreate_time() * 1000L));
            if (item.getDelete_time() != 0) {
                cate.setDeleted(1);
            }
            cateMapper.insertCate(cate);
        });
    }

    /**
     * 格式化分类表数据
     */
    @Override
    public void formatTypeData() {
        List<Type_old> typeOlds = deptMapper.selectTypeOldList();
        typeOlds.forEach(item -> {
            Type type = new Type();
            type.setId(Long.valueOf(item.getId()));
            type.setParentId(Long.valueOf(item.getParent_id()));
            type.setCateId(Long.valueOf(item.getCate_id()));
            type.setName(item.getName());
            type.setSpecId(Long.valueOf(item.getSpec_id()));
            type.setBrandId(Long.valueOf(item.getBrand_id()));
            type.setPackages(item.getPackages());
            type.setDemand(item.getDemand());
            type.setOther(item.getOther());
            type.setTag(Long.valueOf(item.getTag()));
            type.setPrice(item.getPrice());
            type.setCreateTime(new Date(item.getCreate_time() * 1000L));
            if (item.getDelete_time() != 0) {
                type.setDeleted(1);
            }
            typeMapper.insertType(type);
        });
    }

    /**
     * 格式化竞品规格数据
     */
    @Override
    public void formatSpecData() {
        List<Spec_old> specOlds = deptMapper.selectSpecOldList();
        specOlds.forEach(item -> {
            Spec spec = new Spec();
            spec.setId(Long.valueOf(item.getId()));
            spec.setName(item.getName());
            spec.setCreateTime(new Date(item.getCreate_time() * 1000L));
            if (item.getDelete_time() != 0) {
                spec.setDeleted(1);
            }
            specMapper.insertSpec(spec);
        });
    }

    /**
     * 格式化单位数据
     */
    @Override
    public void formatBrand() {
        List<Brand_old> brandOlds = deptMapper.selectBrandOldList();
        brandOlds.forEach(item -> {
            Brand brand = new Brand();
            brand.setId(Long.valueOf(item.getId()));
            brand.setName(item.getName());
            brand.setCreateTime(new Date(item.getCreate_time() * 1000L));
            if (item.getDelete_time() != 0) {
                brand.setDeleted(1);
            }
            brandMapper.insertBrand(brand);
        });
    }
}
